import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { differenceInMinutes, differenceInSeconds } from 'date-fns';
import { NzMessageService, NzModalService, NzUploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
import { LIVE_COVER_UPLOAD, LIVE_EDITOR_UPLAOD, LIVE_INFO, LIVE_MODIFY, LIVE_PLAY_URL, LIVE_REDORE_LIST, ossUri, PAGE_MODEL_ALL, VOD_CATEGORY, VOD_FIND, VOD_SAVE } from 'src/app/service/action_type';
import { LivelibService } from 'src/app/service/livelib.service';
import { OprationService } from 'src/app/service/opration.service';
import { RequestService } from 'src/app/service/request.service';
import { API_CONFIG } from 'src/app/service/service.module';
import { PlayerComponent } from 'src/app/component/player/player.component';

import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn';
import * as DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document'; //编辑器js文件生成的类的名字
import { HttpClient } from '@angular/common/http';
declare var io: any;
declare var returnCitySN: any;

@Component({
  selector: 'app-live-detail',
  templateUrl: './live-detail.component.html',
  styleUrls: ['./live-detail.component.less']
})
export class LiveDetailComponent implements OnInit {

  Editor = DecoupledEditor;
  config = {
    toolbar: [
      'heading',
      '|',
      'fontfamily',
      'fontsize',
      'alignment',
      'highlight',
      'bold',
      'italic',
      'underline',
      'strikethrough',
      'imageUpload',
      '|',
      'undo',
      'redo'
    ],
    language: 'zh-cn',
    fontSize: {
      options: [12, 14, 16, 20, 26, 32, 36, 40, 44, 48, 64, 96, 128]
    },
    highlight: {
      options: [{
        model: 'yellowMarker',
        class: 'pen-yellow',
        title: '黄',
        color: 'var(--ck-highlight-marker-yellow)',
        type: 'pen'
      },
      {
        model: 'greenMarker',
        class: 'pen-green',
        title: '绿',
        color: 'var(--ck-highlight-marker-green)',
        type: 'pen'
      },
      {
        model: 'pinkMarker',
        class: 'pen-pink',
        title: '粉',
        color: 'var(--ck-highlight-marker-pink)',
        type: 'pen'
      },
      {
        model: 'blueMarker',
        class: 'pen-blue',
        title: '蓝',
        color: 'var(--ck-highlight-marker-blue)',
        type: 'pen'
      },
      {
        model: 'redPen',
        class: 'pen-red',
        title: '红',
        color: 'var(--ck-highlight-pen-red)',
        type: 'pen'
      },
      {
        model: 'orange',
        class: 'pen-orange',
        title: '橙',
        color: '#faad14',
        type: 'pen'
      },
      {
        model: 'gray9',
        class: 'pen-999',
        title: '灰色9',
        color: '#999',
        type: 'pen'
      },
      {
        model: 'gray6',
        class: 'pen-666',
        title: '灰色6',
        color: '#666',
        type: 'pen'
      },
      {
        model: 'black3',
        class: 'pen-333',
        title: '黑色3',
        color: '#333',
        type: 'pen'
      }]
    }
  };

  @ViewChild('watchUrl', { static: false }) watchUrl: ElementRef;
  @ViewChild('watchUrl2', { static: false }) watchUrl2: ElementRef;
  @ViewChild('watchUrl3', { static: false }) watchUrl3: ElementRef;
  @ViewChild('pushUrl', { static: false }) inputPushUrl: ElementRef;
  @ViewChild('pushKey', { static: false }) inputPushKey: ElementRef;
  @ViewChild('watchIframe', { static: false }) watchIframe: ElementRef;
  @ViewChild('player', { static: false }) player: PlayerComponent;
  @ViewChild('playKey1', { static: false }) playKey1: ElementRef;
  @ViewChild('playKey2', { static: false }) playKey2: ElementRef;
  @ViewChild('playKey3', { static: false }) playKey3: ElementRef;

  validateModifyForm!: FormGroup;
  wxModifyForm!: FormGroup;

  data: any = {};
  secret: any = {
    id: null,
    lastSecretDate: null
  };
  isLoading: boolean = false;
  messagePanelIndex: number = 0;
  watchTotalCount: number = 0;
  watchSelectData = {
    liveId: 0,
    status: 0,
    type: 2,
    pagesize: 100,
    pageindex: 1
  };
  watchList: any[] | null = null;
  leaveWatchTotalCount: number = 0;
  leaveWatchSelectData = {
    liveId: 0,
    status: 1,
    type: 2,
    pagesize: 100,
    pageindex: 1
  };
  leaveWatchList: any[] | null = null;
  messageTotalCount: number = 0;
  messageSelectData = {
    liveId: 0,
    pagesize: 100,
    pageindex: 1
  };
  messageList: any[] | null = null;
  forbidMessageTotalCount: number = 0;
  forbidMessageSelectData = {
    liveId: 0,
    pagesize: 100,
    pageindex: 1,
    isRefuse: true
  };
  forbidMessageList: any[] | null = null;
  inputMessage: string = '';
  isEditShow: boolean = false;
  ossUrl: string = ossUri;
  uploadUrl: string | null = '';
  headers: any | null = null;
  isShareShow: boolean = false;
  watchUrlString: string = '';
  qrImageUrl: string = '';
  watchIframeString: string = '';
  isHistoryShow: boolean = false;
  videoPushTime: string | null = null;
  videoList: any[] | null = null;
  isTemplateShow: boolean = false;
  isContentShow: boolean = false;
  pageModelList: any[] | null = null;
  editLoading: boolean = false;
  content: string = '';
  watchMultiple: number = 1;
  position: string = 'lt';
  contentMod: string = '自编内容';
  categoryList: any[] | null = null;
  socket1: any;
  $socket = null;
  socketSignId = this.guid();
  ip = this.getIp();
  calcData: any | null = null;
  settleData: any | null = null;

  //初始化加载
  onReady(editor: any) {
    editor.ui.getEditableElement().parentElement.insertBefore(
      editor.ui.view.toolbar.element,
      editor.ui.getEditableElement(),
    )
    editor.plugins.get('FileRepository').createUploadAdapter = (loader: any) => {
      return new UploadAdapter(loader, this.uri, this.http);
    };
  }
  //内容变化时
  onChange() {

  }

  setContent() {
    this.content = this.data['content_' + this.position];
    this.watchMultiple = this.data['watchMultiple_' + this.position];
    this.contentMod = this.data['contentMod_' + this.position];
  }

  bindTemplate(id: number) {
    this.data['pageModelId'] = id;
    this.requestService.post(LIVE_MODIFY, { 'id': this.data['id'], 'pageModelId': id }).subscribe(result => {
      this.msg.success('绑定成功');
    });
  }

  saveConent() {
    let data = {};
    data['id'] = this.data['id'];
    data['content_' + this.position] = this.content;
    this.data['content_' + this.position] = this.content;
    this.requestService.post(LIVE_MODIFY, data).subscribe(result => {
      this.msg.success('保存成功');
    });
  }

  conentAfterOpen() {
    this.editLoading = true;
  }

  setContentMod(mod: string) {
    this.contentMod = mod;
    let data = {};
    data['id'] = this.data['id'];
    data['contentMod_' + this.position] = mod;
    this.data['contentMod_' + this.position] = mod;
    this.requestService.post(LIVE_MODIFY, data).subscribe(result => {

    });
  }

  setContentPosition(position: string) {
    this.position = position;
    this.setContent();
  }

  setWatchMultiple() {
    let data = {};
    data['id'] = this.data['id'];
    data['watchMultiple_' + this.position] = this.watchMultiple;
    this.data['watchMultiple_' + this.position] = this.watchMultiple;
    this.requestService.post(LIVE_MODIFY, data).subscribe(result => {
    });
  }

  contentShow(isShow: boolean) {
    this.isContentShow = isShow;
    if (!isShow)
      this.editLoading = false;
  }

  templateShow(isShow: boolean) {
    this.isTemplateShow = isShow;
  }

  historyShow(isShow: boolean) {
    this.isHistoryShow = isShow;
  }

  shareShow(isShow: boolean) {
    this.isShareShow = isShow;
  }

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('只能上传图片!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片必须小于 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.isLoading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.data['logo'] = info.file.response.name;
        this.isLoading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.isLoading = false;
        break;
    }
  }
  handlewxCoverChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.isLoading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.data['wxShareCover'] = info.file.response.name;
        this.isLoading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.isLoading = false;
        break;
    }
  }

  modifyForm() {
    for (const i in this.validateModifyForm.controls) {
      this.validateModifyForm.controls[i].markAsDirty();
      this.validateModifyForm.controls[i].updateValueAndValidity();
    }
    if (this.validateModifyForm.status == "VALID") {
      var data = this.validateModifyForm.value;
      data['id'] = this.data['id'];
      data['logo'] = this.data['logo'];
      if (data.liveDate && data.liveDate.length > 1) {
        data['startDate'] = data.liveDate[0];
        data['endDate'] = data.liveDate[1];
      }
      this.livelibService.save(data).subscribe(result => {
        if (result['code'] === 'success')
          this.msg.success('您的直播修改成功!');
        else
          this.msg.error(result['data']);
      });
    }
  }
  modifyWxShare() {
    for (const i in this.wxModifyForm.controls) {
      this.wxModifyForm.controls[i].markAsDirty();
      this.wxModifyForm.controls[i].updateValueAndValidity();
    }
    if (this.wxModifyForm.status == "VALID") {
      var data = this.wxModifyForm.value;
      data['id'] = this.data['id'];
      data['startDate'] = this.data['startDate'];
      data['endDate'] = this.data['endDate'];
      data['title'] = this.data['title'];
      data['wxShareCover'] = this.data['wxShareCover']

      this.livelibService.save(data).subscribe(result => {
        if (result['code'] === 'success')
          this.msg.success('您的直播修改成功!');
        else
          this.msg.error(result['data']);
      });
    }
  }
  messagePanelClick(index: number) {
    this.messagePanelIndex = index
  }

  sendMessage() {
    if (this.inputMessage !== '') {
      const danmu = {
        content: this.inputMessage,
        ip: window.sessionStorage["phone"],
        roomId: this.data['roomId'],
        userName: window.sessionStorage["username"],
        userGuid: this.data['userId'].toString(),
        headPath: 'https://manage.ysjlive.com/assets/images/header-default.png',
      };
      this.$socket.emit("send", danmu);
    }
  }

  editShow(isShow: boolean) {
    this.isEditShow = isShow;
  }

  setMouseOver(index: number, isOver: boolean) {
    this.messageList[index]['isOver'] = isOver;
  }

  delete() {
    this.modalService.confirm({
      nzTitle: '信息提示',
      nzContent: '确定要删除此直播间吗？',
      nzClosable: false,
      nzOnOk: () => {
        this.livelibService.delete(this.data['id']).subscribe(result => {
          this.oprationService.tips(result, '直播删除成功');
          this.router.navigateByUrl('/main/live');
        });
      }
    });
  }

  setMessage(id: number, refuse: number) {
    this.modalService.confirm({
      nzTitle: '信息提示',
      nzContent: refuse === 1 ? '确定要将此用户禁言吗?' : '确定要解除此用户的禁言吗?',
      nzClosable: false,
      nzOnOk: () => {
        if (refuse === 0) {
          this.livelibService.deRefuse(id).subscribe(result => {
            this.msg.success('解除用户禁言成功');
            this.getMessageList();
            this.getForbidMessageList();
          })
        }
        else if (refuse === 1) {
          this.livelibService.refuse(id).subscribe(result => {
            this.msg.success('设置用户禁言成功');
            this.getMessageList();
            this.getForbidMessageList();
          })
        }
      }
    });
  }

  getWatchList() {
    this.isLoading = true;
    this.livelibService.watchPage(this.watchSelectData).subscribe(result => {
      this.isLoading = false;
      this.watchTotalCount = result['data']['count'];
      this.watchList = result['data']['items'];
      this.watchList.forEach(item => {
        if (item['endDate']) {
          let second = differenceInSeconds(new Date(item['endDate']), new Date(item['startDate']));
          let h = 0;
          let m = 0;
          let s = 0;
          if (second >= 3600) {
            let leftS = second % 3600;
            h = (second - leftS) / 3600;
            second = leftS;
          }
          if (second >= 60) {
            let leftS = second % 60;
            m = (second - leftS) / 60;
            second = leftS;
          }
          s = second;
          let time = [];
          if (h > 0)
            time.push(`${h}小时`)
          if (m > 0)
            time.push(`${m}分`)
          if (s > 0)
            time.push(`${s}秒`)
          item['minute'] = time.join('');
        }
      });
    });
  }

  getLeaveWatchList() {
    this.isLoading = true;
    this.livelibService.watchPage(this.leaveWatchSelectData).subscribe(result => {
      this.isLoading = false;
      this.leaveWatchTotalCount = result['data']['count'];
      this.leaveWatchList = result['data']['items'];
      this.leaveWatchList.forEach(item => {
        if (item['endDate']) {
          let second = differenceInSeconds(new Date(item['endDate']), new Date(item['startDate']));
          let h = 0;
          let m = 0;
          let s = 0;
          if (second >= 3600) {
            let leftS = second % 3600;
            h = (second - leftS) / 3600;
            second = leftS;
          }
          if (second >= 60) {
            let leftS = second % 60;
            m = (second - leftS) / 60;
            second = leftS;
          }
          s = second;
          let time = [];
          if (h > 0)
            time.push(`${h}小时`)
          if (m > 0)
            time.push(`${m}分`)
          if (s > 0)
            time.push(`${s}秒`)
          item['minute'] = time.join('');
        }
      });
    });
  }

  getMessageList() {
    this.isLoading = true;
    this.livelibService.messagePage(this.messageSelectData).subscribe(result => {
      this.isLoading = false;
      this.messageTotalCount = result['data']['count'];
      this.messageList = result['data']['items'];
    });
  }

  getForbidMessageList() {
    this.isLoading = true;
    this.livelibService.messagePage(this.forbidMessageSelectData).subscribe(result => {
      this.isLoading = false;
      this.forbidMessageTotalCount = result['data']['count'];
      this.forbidMessageList = result['data']['items'];
    });
  }

  getHistoryList() {
    //查询视频列表
    this.requestService.get(VOD_FIND + this.data['roomId']).subscribe(x => {
      let vodlist: any[] = x['data'];
      this.livelibService.requestApi({
        method: 'get',
        path: LIVE_REDORE_LIST + this.data['roomId']
      }).subscribe(result => {
        this.videoList = result['data'];
        let totalSecond = 0;
        this.videoList.forEach(item => {
          let second = differenceInSeconds(new Date(item['EndTime']), new Date(item['StartTime']));
          totalSecond += second;
          let h = 0;
          let m = 0;
          let s = 0;
          if (second >= 3600) {
            let leftS = second % 3600;
            h = (second - leftS) / 3600;
            second = leftS;
          }
          if (second >= 60) {
            let leftS = second % 60;
            m = (second - leftS) / 60;
            second = leftS;
          }
          s = second;
          let time = [];
          if (h > 0)
            time.push(`${h}小时`)
          if (m > 0)
            time.push(`${m}分`)
          if (s > 0)
            time.push(`${s}秒`)
          item['minute'] = time.join('');
          if (vodlist.find(ix => ix.PK_LiveRecordGuid === item['PK_LiveRecordGuid'])) {
            item['isSave'] = true;
          } else {
            item['isSave'] = false;
          }
        });
        let h = 0;
        let m = 0;
        let s = 0;
        if (totalSecond >= 3600) {
          let leftS = totalSecond % 3600;
          h = (totalSecond - leftS) / 3600;
          totalSecond = leftS;
        }
        if (totalSecond >= 60) {
          let leftS = totalSecond % 60;
          m = (totalSecond - leftS) / 60;
          totalSecond = leftS;
        }
        s = totalSecond;
        this.videoPushTime = `${h}小时${m}分${s}秒`;
      });
    });
  }

  cancelSave(no: number) {
    this.videoList[no]["isSaving"] = false;
  }

  goSave(no: number) {
    if (!this.categoryList) {
      this.requestService.get(VOD_CATEGORY).subscribe(result => {
        this.categoryList = result['data'];
      })
    }
    this.videoList[no]["isSaving"] = true;
  }

  saveVod(no: number) {
    if (this.videoList[no]['categoryId']) {
      this.modalService.confirm({
        nzTitle: '信息提示',
        nzContent: '确定要保存至点播视频库吗?',
        nzClosable: false,
        nzOnOk: () => {
          let data = this.videoList[no];
          this.requestService.post(VOD_SAVE, {
            PK_LiveRecordGuid: data['PK_LiveRecordGuid'],
            roomId: data['FK_LiveRoomGuid'],
            categoryId: data['categoryId'],
            title: data['Name'],
            save_supplier: 'oss',
            introduce: data['Describe'],
            startDate: data['StartTime'],
            endDate: data['EndTime'],
            logo: data['Cover'],
            playUrl: data['PlayUrl']
          }).subscribe(result => {
            data['isSave'] = true;
            data['isSaving'] = false;
            this.oprationService.tips(result, '存储至点播视频库成功');
          });
        }
      });
    }
    else {
      this.msg.error('请选择要保存的库');
    }
  }
  changeAllowLiveStream(e) {
    this.modalService.confirm({
      nzTitle: e ? '确定要开启推流吗' : '确定要关闭推流吗',
      nzOnOk: () => {
        this.livelibService.save({
          id: this.data['id'],
          allowLiveStream: e,
          title: this.data['title'],
          startDate: this.data['startDate'],
          endDate: this.data['endDate'],
        }).subscribe(result => {
          if (result['code'] === 'success') {
            this.msg.success('修改成功!');
            this.data["allowLiveStream"] = e
          }
          else
            this.msg.error(result['data']);
        });
      }
    })
  }
  copy(inputId: string) {
    if (inputId === 'pushUrl') {
      this.inputPushUrl.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'pushKey') {
      this.inputPushKey.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'watchUrl') {
      this.watchUrl.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'watchUrl2') {
      this.watchUrl2.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'watchUrl3') {
      this.watchUrl3.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'watchIframe') {
      this.watchIframe.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'playKey1') {
      this.playKey1.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'playKey2') {
      this.playKey2.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
    else if (inputId === 'playKey3') {
      this.playKey3.nativeElement.select();
      document.execCommand('copy');
      this.msg.success('以复制到剪切板');
    }
  }

  resetSecret() {
    if (!this.secret.id || this.secret.id !== this.data['id'] || !this.secret.lastSecretDate || differenceInMinutes(new Date(), this.secret.lastSecretDate) >= 100) {
      this.livelibService.getSecret(this.data['id']).subscribe(result => {
        if (result['code'] === 'success') {
          this.data = result['data'];
          this.secret.id = this.data['id']
          this.secret.lastSecretDate = new Date();
        }
        else {
          this.data['pushKey'] = result['data'];
        }
      });
    }
  }

  disconnect(id: number) {
    this.modalService.confirm({
      nzTitle: '信息提示',
      nzContent: '确定要断开此直播吗？',
      nzClosable: false,
      nzOnOk: () => {
        this.livelibService.disconnect(id).subscribe(result => {
          if (result['code'] === 1) {
            this.secret.id = null;
            this.secret.lastSecretDate = null;
            this.modalService.success({
              nzTitle: '信息提示',
              nzContent: result['msg'],
              nzClosable: false
            });
          }
          else {
            this.modalService.error({
              nzTitle: '信息提示',
              nzContent: result['msg'],
              nzClosable: false
            });
          }
          //this.getlist();
        });
      }
    });
  }

  setSocket() {
    this.socket1 = io(this.uri);
    let that = this;
    that.socket1.on('connect', function () {
      console.log('管理端Socket连接成功...');
    });
    // 监听弹幕
    that.socket1.on('message', (data: any) => {
      console.log('------------message----------------')
      if (that.messageList.findIndex(item => item.id === data['id']) === -1 && data['roomId'] === that.data['roomId'])
        that.messageList.splice(0, 0, data);
    });
    // 监听新用户连接
    that.socket1.on('user-connect', (data: any) => {
      console.log('------------connect----------------')
      if (that.watchList.findIndex(item => item.id === data['id']) === -1 && data['roomId'] === that.data['roomId'])
        that.watchList.splice(0, 0, data);
    });
    // 监听用户释放连接
    that.socket1.on('user-release', (data: any) => {
      console.log('------------release----------------')
      if (data['roomId'] === that.data['roomId']) {
        let index = that.watchList.findIndex(item => item.id === data['id']);
        if (index > -1)
          that.watchList.splice(index, 1);
        if (that.leaveWatchList.findIndex(item => item.id === data['id']) === -1) {
          if (data['endDate']) {
            let second = differenceInSeconds(new Date(data['endDate']), new Date(data['startDate']));
            let h = 0;
            let m = 0;
            let s = 0;
            if (second >= 3600) {
              let leftS = second % 3600;
              h = (second - leftS) / 3600;
              second = leftS;
            }
            if (second >= 60) {
              let leftS = second % 60;
              m = (second - leftS) / 60;
              second = leftS;
            }
            s = second;
            let time = [];
            if (h > 0)
              time.push(`${h}小时`)
            if (m > 0)
              time.push(`${m}分`)
            if (s > 0)
              time.push(`${s}秒`)
            data['minute'] = time.join('');
          }
          that.leaveWatchList.splice(0, 0, data);
        }
      }
    });
    //监听直播断开结算
    that.socket1.on('user-settle', (data: any) => {
      console.log('------------settle----------------');
      if (data.roomId === that.data.roomId)
        that.settleData = data;
    });
    //监听费用不足强制断开结算
    that.socket1.on('user-calc', (data: any) => {
      console.log('------------calc----------------');
      let calcData = data.find((item: any) => item.roomId === that.data.roomId);
      if (calcData) {
        that.calcData = calcData;
        if (calcData.isSettle)
          that.settleData = calcData;
      }
    });
  }
  guid() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (
      S4() +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      S4() +
      S4()
    );
  }
  getIp() {
    return returnCitySN["cip"];
  }
  constructor(
    private requestService: RequestService,
    private msg: NzMessageService,
    private livelibService: LivelibService,
    private oprationService: OprationService,
    private modalService: NzModalService,
    private route: ActivatedRoute,
    private router: Router,
    private fb: FormBuilder,
    @Inject(API_CONFIG) private uri: string,
    private http: HttpClient
  ) { }

  ngOnInit(): void {
    let liveId = this.route.snapshot.params.id;
    this.messageSelectData['liveId'] = liveId;
    this.watchSelectData['liveId'] = liveId;
    this.leaveWatchSelectData['liveId'] = liveId;
    this.forbidMessageSelectData['liveId'] = liveId;
    this.getMessageList();
    this.getWatchList();
    this.getLeaveWatchList();
    this.getForbidMessageList();
    this.uploadUrl = this.uri + LIVE_COVER_UPLOAD;
    let ticket = window.sessionStorage['ticket'];
    this.headers = { 'Authorization': 'BasicAuth ' + ticket };
    this.validateModifyForm = this.fb.group({
      title: [null, [Validators.required]],
      liveDate: [null, [Validators.required]],
      introduce: [null, [Validators.required]]
    });
    this.wxModifyForm = this.fb.group({
      wxShareTitle: [null, [Validators.required]],
      wxShareDesc: [null, [Validators.required]],
      wxShareCover: [null, [Validators.required]],
    });
    this.setSocket();
    this.requestService.get(PAGE_MODEL_ALL).subscribe(result => {
      this.pageModelList = result['data'];
    })
    this.requestService.get(`${LIVE_INFO}${liveId}`).subscribe(result => {
      this.data = result['data'];
      if (!result['data']['contentMod'] || result['data']['contentMod'] === '')
        this.data['contentMod'] = '自编内容';
      this.setContent();

      this.getHistoryList();
      this.livelibService.qrcode(this.data['roomId']).subscribe((result: string) => {
        this.qrImageUrl = result['data'];
      });
      this.watchUrlString = LIVE_PLAY_URL + '/' + this.data['roomId']
      this.watchIframeString = '<iframe id="VRPlayer" src="' + this.watchUrlString + '" style="width:100%;height:100%;border:none;" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>';
      this.resetSecret();
      let _data = JSON.parse(JSON.stringify(this.data))
      if (!this.data['wxShareTitle']) this.data['wxShareTitle'] = _data['title']
      if (!this.data['wxShareDesc']) this.data['wxShareDesc'] = _data['introduce']
      if (!this.data['wxShareCover']) this.data['wxShareCover'] = _data['logo']
      this.validateModifyForm.setValue({
        title: this.data['title'],
        liveDate: [this.data['startDate'], this.data['endDate']],
        introduce: this.data['introduce']
      });
      this.wxModifyForm.setValue({
        wxShareTitle: this.data['wxShareTitle'],
        wxShareDesc: this.data['wxShareDesc'],
        wxShareCover: this.data['wxShareCover'],
      });
      this.$socket = io(`wss://canvasio2.lessonplan.cn/live`);
      this.$socket.emit("joinRoom", {
        roomId: this.data['roomId'],
        ip: this.ip,
        socketSignId: this.socketSignId,
      });
      this.$socket.on('handelSend', ({ content, userName, headPath, ip }) => {
        this.player.sendDanmu(content);
        //将接收到的弹幕数据push到this.messageList
      })
      this.$socket.on('violation', () => {
        //发送的弹幕违规
        this.msg.error("弹幕含有违规词汇")
      });

      this.isLoad = true
    });

  }
  isLoad = false
  ngOnDestroy() {
    if (this.$socket) this.$socket.close();
    this.socket1.disconnect();
  }

}

export class UploadAdapter {
  loader: any;
  uri: string;
  http: HttpClient;
  constructor(loader: any, uri: string, http: HttpClient) {
    this.loader = loader
    this.uri = uri;
    this.http = http;
    this.upload()
  }
  upload() {
    return new Promise(async (resolve, reject) => {
      let file = await this.loader.file.then(res => res);
      const formData: FormData = new FormData();
      formData.append('image', file);
      this.http.post(this.uri + LIVE_EDITOR_UPLAOD, formData).subscribe((res: any) => {
        resolve({
          default: res.url
        })
      })
    });
  }
}
